<?php


namespace App\Process;


use EasySwoole\Component\Process\AbstractProcess;
use EasySwoole\Component\WaitGroup;
use EasySwoole\EasySwoole\Logger;
use EasySwoole\EasySwoole\Trigger;
use EasySwoole\FastCache\Cache;
use Swoole\Coroutine;

class FastCacheQueue extends AbstractProcess
{

    protected function run($arg)
    {
//        $wait = new WaitGroup();
        foreach (range(0, 4) as $v) {
            go(function () {
                while (true) {
                    $job = Cache::getInstance()->getJob('fast_cache_queue');// Job对象或者null
                    if ($job === null) {
//                        echo \time() . '--没有任务', PHP_EOL;
                        Coroutine::sleep(1);
                    } else {
                        // 执行业务逻辑
//                        var_dump($job);
                        // 执行完了要删除或者重发，否则超时会自动重发
                        Cache::getInstance()->deleteJob($job);
                    }
                }
            });
        }
        // 等待协程结束在退出
//        $wait->wait();
    }

    /**
     * 当有主进程对子进程发送消息的时候，会触发的回调，触发后，务必使用
     * $process->read()来读取消息
     **/
    protected function onPipeReadable(\Swoole\Process $process)
    {
//        var_dump($process->read());
        echo '主进程对子进程发来消息了';
    }

    /**
     * 当该进程退出的时候，会执行该回调
     */
    protected function onShutDown()
    {
        echo '进程退出了';
        //todo 可以设置邮件发送监控 等
    }

    /**
     * @param \Throwable $throwable
     * @param mixed ...$args
     * 当该进程出现异常的时候，会执行该回调
     */
    protected function onException(\Throwable $throwable, ...$args)
    {
        go(function () use ($throwable) {
            $msg = $throwable->getFile() . ' line: ' . $throwable->getLine() . ' msg: ' . $throwable->getMessage();
            $path = __DIR__ . '/Log/process/' . date('Y-m') . '/' . date('Y-m-d') . '_error.log';
            file_put_contents($path, $msg . PHP_EOL, FILE_APPEND);
        });
    }
}
